
//ARTISTS.JS
//shows the artists in the library
// Author: Wilco

function artistsPage() {}
artistsPage.prototype.constructor = artistsPage;
artistsPage.prototype =
{
    templateData: '',
    artistsJSON: '',
    artistsData: {},
    title: 'Artists',
	hooksData: null,
	listTmpl: null,
	searchInput: null,
	filters: '',
    loadPage: function()
    {
        this.onOutput = function(title,pageTemplate) { ProcessPageOutput(title,pageTemplate,'',true); }
        this.loadDefaults();
        //Load template data
        LoadFile(SkinDir + 'artists.html', this.onLoadTemplate.bind(this));
    },
    loadDefaults: function()
    {  
       //No Defaults
    },
    onLoadTemplate: function(response)
    {
        this.templateData = response;
        this.loadData();
    },
    loadData: function()
    {
		var url = ServiceDir;
		
		if (gPageData['artists']['year'])
		{	
            url = url + 'year/' + gPageData['artists']['year'] + '/';
            this.title = gPageData['artists']['year'];
			this.filters = this.filters + '&year=' + gPageData['artists']['year'];
        }
		if (gPageData['artists']['genre'])
		{
            url = url + 'genre/' + gPageData['artists']['genre'] + '/';
            this.title = gPageData['artists']['genre'];
			this.filters = this.filters + '&genre=' + gPageData['albums']['genre'];
        }
		if (gPageData['artists']['album'])
		{
            url = url + 'album/' + gPageData['artists']['album'] + '/';
            this.title = gPageData['artists']['album'];
			this.filters = this.filters + '&album=' + gPageData['albums']['album'];
        }

        url = url + 'artists'; 
        LoadFile(url, this.onLoadData.bind(this));
    },
    onLoadData: function(response)
    {
       this.artistsJSON = response;
       this.generateOutput();
    },
    generateOutput: function()
    {
        try
        {    this.artistsData = eval("(" + this.artistsJSON + ")"); }
        catch (e)
        {    showError('Cannot understand service data'); return; }        

		var tmpl = new Template();
		tmpl.load(this.templateData);
        
        this.artistsData.sort(function(a,b){ if (a.name<b.name) return -1; else if (a.name>b.name) return 1; else return 0;});
        this.listTmpl = tmpl.removeSubTemplate('list');
        this.onOutput(this.title,tmpl);
		
		
		//Hook events
		$('#SearchInput').bind('keyup',SearchUpdate);
		
		this.updateList(this.artistsData);
    },
	updateList: function(artists)
	{
        var tmpl = this.listTmpl.clone();
		var headertmpl = tmpl.removeSubTemplate('header');
		var itemtmpl = tmpl.removeSubTemplate('item');
        var items = [];
        var newtmpl = null;
		var prevHeader = '';
		var header = '';
		//Sort list
		artists.sort(this.sortArtists);
		
		for(var i=0;i<artists.length;i++)
		{
            if (artists[i].name == null || artists[i].name == "null") continue; //FIXME: this shouldnt happen
            
			header = this.headerGroup(artists[i].name);
            if (header != prevHeader)
            {
                newtmpl = headertmpl.clone();
                newtmpl.addData({ 'group_title': header.toUpperCase() });
                items.push(newtmpl);
                prevHeader = header;
            }
                
            newtmpl = itemtmpl.clone();
            newtmpl.addData({    artist: artists[i].name,
								 index: i,
                            artist_uri: encodeURIComponent(artists[i].name),
                        });
            items.push(newtmpl);
		}
		
		tmpl.addData({ filters: this.filters });
		tmpl.addSubTemplate('item',items);
		document.getElementById('pagelist').innerHTML = tmpl.parse();
	},
	sortArtists: function(artistA,artistB)
	{
		if (artistA.name == null) return -1;
		if (artistB.name == null) return -1;
		
		artistA = artistA.name.toLowerCase();
		artistB = artistB.name.toLowerCase();
            
		if (artistA.length > 4 && artistA.substring(0,4) == 'the ')
			artistA = artistA.substr(4);
		else
			artistA = artistA.substr(0);
			
		if (artistB.length > 4 && artistB.substring(0,4) == 'the ')
			artistB = artistB.substr(4);
		else
			artistB = artistB.substr(0);
		
		if (artistA < artistB) return -1;
		if (artistA > artistB) return 1;
		return 0;
	},
	headerGroup: function(artist)
	{
		artist = artist.toLowerCase();
            
		if (artist.length > 4 && artist.substring(0,4) == 'the ')
			artist = artist.charCodeAt(4);
		else
			artist = artist.charCodeAt(0);
			
		if (artist < 61) return ' ';			//ignore before A
		return String.fromCharCode(artist);
	},
	runSearch: function(searchStr)
	{
		var artists = this.artistsData;
		artists = LocalSearch(artists,['name'],searchStr);
		this.updateList(artists);
	},
    onOutput: function(){},
}
function SearchUpdate(eventObj)
{
	var str = $('#SearchInput').val();
	gCurrentPage.runSearch(str);
}

function ArtistItemButton_Click(el,i)
{
	CreateMediaItemMenu(gCurrentPage.hooksData,gCurrentPage.albumsData[i]);
	ShowMenu();
}


gLastScriptLoaded = new artistsPage();
gScriptLoaded();